package com.cmdi.mq.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cmdi.mq.constant.CodeConstants;
import com.cmdi.mq.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * @Description: JwtCheckFilter：当用户访问其他资源时，首先校验redis中是否存在这个token。
 * @Author: gaozb
 */
@Slf4j
@Configuration
@RefreshScope
public class JwtCheckFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${ignoreauth.urls:/swagger-ui.html}")
    private Set<String> noRequireTokenUris;

    @PostConstruct
    public void doInit() {
        log.info("noRequireTokenUris: {}", noRequireTokenUris);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        //该接口是否需要token 才能访问
        if(noRequireTokenUris.contains(path)) {
            log.info("{} need not token", path);
            return chain.filter(exchange);
        }
        //取出用户的token
        String userToken = getUserToken(exchange);
        //System.out.println(userToken);
        if(StringUtils.isEmpty(userToken)) {
            return noAuthorizationResult(exchange);
        }
        String userName = getUserInfoFromtoken(userToken);
        if(userName == null) {
            return noAuthorizationResult(exchange);
        }
        String key = SecurityConstants.TOKEN_REDIS_PREFIX + ":" + userName + ":" + userToken;
        //判断用户的token 是否有效
        Boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey != null && hasKey) {
            return chain.filter(exchange);
        }
        return noAuthorizationResult(exchange);
    }

    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null ? null : token.replace("bearer ","") ;
    }

    private String getUserInfoFromtoken(String token) {
        String userName = null;
        try {
            JSONObject jwtJson = JSON.parseObject(JwtHelper.decode(token).getClaims());
            userName = jwtJson.getString("user_name");
        } catch (Exception e) {
            log.error("错误原因", e);
        }
        return userName;
    }

    private Mono<Void> noAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type","application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED) ;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(CodeConstants.CODE_VALUE, CodeConstants.TOKEN_ERROR_CODE) ;
        jsonObject.put(CodeConstants.MSG_VALUE, CodeConstants.TOKEN_ERROR_MESSAGE) ;
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap)) ;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}